const { path, fs, getMatchingFolderPath } = require('../scripts/common.js');
const { shell } = require('electron');
const { exec } = require('child_process');
const marked = require('marked');

// 配置 marked 选项
marked.setOptions({
    breaks: true, // 支持 GitHub 风格的换行
    gfm: true,    // 支持 GitHub 风格的 Markdown
    headerIds: true,
    mangle: false,
    sanitize: false // 允许 HTML 标签
});

// 格式化JSON显示
function formatJsonDisplay(data) {
    let html = '<div class="formatted-json">';
    
    if (typeof data !== 'object' || data === null) {
        return `<span class="json-value">${data}</span>`;
    }
    
    if (Array.isArray(data)) {
        data.forEach((item, index) => {
            html += `<div class="json-item">[${index}] ${formatJsonDisplay(item)}</div>`;
        });
    } else {
        Object.entries(data).forEach(([key, value]) => {
            html += `<div class="json-item">
                <span class="json-key">${key}:</span> `;
            
            if (value === null) {
                html += '<span class="json-null">null</span>';
            } else if (Array.isArray(value)) {
                html += '<ul class="json-list">';
                value.forEach(item => {
                    html += `<li>${formatJsonDisplay(item)}</li>`;
                });
                html += '</ul>';
            } else if (typeof value === 'object') {
                html += formatJsonDisplay(value);
            } else {
                html += `<span class="json-value">${value}</span>`;
            }
            
            html += '</div>';
        });
    }
    
    html += '</div>';
    return html;
}

// 处理文件点击事件
function handleFileClick(filePath, fileName) {
    const ext = path.extname(fileName).toLowerCase();
    
    try {
        switch (ext) {
            case '.json':
                const content = fs.readFileSync(filePath, 'utf8');
                document.getElementById('fileContent').innerHTML = formatJsonDisplay(JSON.parse(content));
                break;
                
            case '.md':
            case '.markdown':
                const mdContent = fs.readFileSync(filePath, 'utf8');
                document.getElementById('fileContent').innerHTML = `
                    <div class="markdown-content">
                        ${marked.parse(mdContent)}
                    </div>`;
                break;
                
            case '.txt':
            case '.js':
            case '.css':
                const textContent = fs.readFileSync(filePath, 'utf8');
                document.getElementById('fileContent').innerHTML = `
                    <pre class="code-content">${textContent}</pre>`;
                break;

            case '.exe':
            case '.bat':
                exec(`"${filePath}"`, (error) => {
                    if (error) {
                        console.error('Error executing file:', error);
                        alert('执行文件失败: ' + error.message);
                    }
                });
                break;

            case '.lnk':
                // 读取快捷方式的目标路径并打开
                shell.openPath(filePath);
                break;

            case '.html':
            case '.pdf':
                // 用默认浏览器打开
                shell.openExternal(`file://${filePath}`);
                break;

            case '.doc':
            case '.docx':
                // 用 Word 打开
                exec(`start winword "${filePath}"`, (error) => {
                    if (error) {
                        console.error('Error opening Word file:', error);
                        shell.openPath(filePath); // 备选方案：使用默认程序打开
                    }
                });
                break;

            case '.xls':
            case '.xlsx':
            case '.csv':
                // 用 Excel 打开
                exec(`start excel "${filePath}"`, (error) => {
                    if (error) {
                        console.error('Error opening Excel file:', error);
                        shell.openPath(filePath); // 备选方案：使用默认程序打开
                    }
                });
                break;

            case '.ppt':
            case '.pptx':
                // 用 PowerPoint 打开
                exec(`start powerpnt "${filePath}"`, (error) => {
                    if (error) {
                        console.error('Error opening PowerPoint file:', error);
                        shell.openPath(filePath); // 备选方案：使用默认程序打开
                    }
                });
                break;
                
            default:
                // 对于其他类型的文件，打开所在位置
                shell.showItemInFolder(filePath);
                break;
        }
    } catch (error) {
        console.error('Error handling file:', error);
        document.getElementById('fileContent').innerHTML = '处理文件失败: ' + error.message;
    }
}

// 递归获取文件夹中的所有文件
function getAllFiles(dirPath) {
    let results = [];
    const items = fs.readdirSync(dirPath);
    
    items.forEach(item => {
        const fullPath = path.join(dirPath, item);
        const stat = fs.statSync(fullPath);
        
        if (!stat.isDirectory()) {
            results.push({
                name: item,
                path: fullPath,
                ext: path.extname(item).toLowerCase()
            });
        }
    });
    
    return results;
}

// 获取文件图标
function getFileIcon(ext) {
    const icons = {
        '.json': '📄',
        '.md': '📝',
        '.markdown': '📝',
        '.txt': '📃',
        '.js': '📜',
        '.css': '🎨',
        '.lnk': '🔗',
        '.exe': '⚙️',
        '.bat': '⚡',
        '.html': '🌐',
        '.pdf': '📕',
        '.doc': '📘',
        '.docx': '📘',
        '.xls': '📗',
        '.xlsx': '📗',
        '.csv': '📊',
        '.ppt': '📙',
        '.pptx': '📙'
    };
    return icons[ext] || '📄';
}

// 成果标签点击事件
document.getElementById('compositionsLabel').onclick = () => {
    const fileContent = document.getElementById('fileContent');
    
    if (fileContent.innerHTML.trim() !== '') {
        fileContent.innerHTML = '';
        document.querySelector('.card-4').innerHTML = '';
        document.querySelector('.pink-card').innerHTML = '';
    } else {
        document.querySelector('.pink-card').innerHTML = '';
    }

    const fileList = document.getElementById('fileList');
    try {
        const matchingFolderPath = getMatchingFolderPath();
        if (matchingFolderPath) {
            const compositionsPath = path.join(matchingFolderPath, 'compositions');
            if (fs.existsSync(compositionsPath)) {
                const files = getAllFiles(compositionsPath);
                
                if (files.length === 0) {
                    fileList.innerHTML = '<div class="file-item">没有找到文件</div>';
                    return;
                }

                fileList.innerHTML = '';
                files.forEach(file => {
                    const div = document.createElement('div');
                    div.className = 'file-item';
                    
                    // 添加文件图标
                    const icon = getFileIcon(file.ext);
                    div.innerHTML = `<span class="file-icon">${icon}</span>${file.name}`;
                    
                    div.onclick = () => {
                        handleFileClick(file.path, file.name);
                        
                        // 更新选中状态
                        document.querySelectorAll('.file-item').forEach(item => {
                            item.classList.remove('selected');
                        });
                        div.classList.add('selected');
                    };
                    fileList.appendChild(div);
                });
            } else {
                fileList.innerHTML = '<div class="file-item">成果文件夹不存在</div>';
            }
        } else {
            fileList.innerHTML = '<div class="file-item">未找到匹配的文件夹</div>';
        }
    } catch (error) {
        console.error('Error:', error);
        fileList.innerHTML = '读取文件夹失败：' + error.message;
    }
};

// 导出需要的函数
module.exports = {
    formatJsonDisplay
}; 